package com.ikangtai.shecare.curve;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.ikangtai.shecare.R;
import com.ikangtai.shecare.common.util.AppLog;

public class WebViewCfg {
    private WebView webview;
    private Context context;
    private ProgressDialog progressDialog;

    public WebViewCfg(WebView webview){
        this.webview = webview;
        this.context = webview.getContext();
    }

    public WebView getCfgedWebView(Context context){
        return getCfgedWebView(context, true);
    }

    public WebView getCfgedWebView(Context context, boolean hasProgressDialog){
        WebSettings webSettings = webview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDomStorageEnabled(true);
        //webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        webSettings.setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = context.getCacheDir().getAbsolutePath();
        webSettings.setAppCachePath(appCachePath);
        webSettings.setAllowFileAccess(true);
        webSettings.setAppCacheEnabled(true);

        webview.requestFocus();

        if(hasProgressDialog) {
            webview.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    AppLog.i("webview " + view.getProgress() + ":" + view.getProgress() + " onPageFinished URL " + url);

                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                        progressDialog = null;
                    }
                    super.onPageFinished(view, url);
                }

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    // TODO Auto-generated method stub
                    AppLog.i("webview onPageStarted URL" + url);
                    showProgressDialog();
                    super.onPageStarted(view, url, favicon);
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    // TODO Auto-generated method stub
                    AppLog.i("webview shouldOverrideUrlLoading URL" + url);
                    return super.shouldOverrideUrlLoading(view, url);
                }

                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    // TODO Auto-generated method stub
                    AppLog.i("webview onReceivedError");
                    super.onReceivedError(view, errorCode, description, failingUrl);
                }
            });

            webview.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    AppLog.i("webview " + newProgress + " === " + view.getProgress() + " : onProgressChanged URL: " + view.getUrl());
                    if (newProgress == 100) {
                        AppLog.i("webview 当前页面加载到100:>>>>>>>>onProgressChanged URL: " + view.getUrl());
                    }
                    super.onProgressChanged(view, newProgress);
                }
            });
        }

        webview.setHorizontalScrollBarEnabled(false);//水平不显示
        webview.setVerticalScrollBarEnabled(false); //垂直不显示

        /**
         * 缓存模式(5种)
         * LOAD_CACHE_ONLY:  不使用网络，只读取本地缓存数据
         * LOAD_DEFAULT:  根据cache-control决定是否从网络上取数据。
         * LOAD_CACHE_NORMAL: API level 17中已经废弃, 从API level 11开始作用同LOAD_DEFAULT模式
         * LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
         * LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
         */
        webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

        /**
         * webview 优化:
         * 1. 提高渲染的优先级
         * 2. 把图片加载放在最后来加载渲染
         * 3. 硬件加速
         */

        // 提高渲染的优先级
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);

        // 把图片加载放在最后来加载渲染
        webview.getSettings().setBlockNetworkImage(true);
        webview.setWebChromeClient(new WebChromeClient() {
                                            @Override
                                            public void onProgressChanged(WebView view, int progress) {
                                                if (progress >= 100)
                                                    webview.getSettings().setBlockNetworkImage(false);
                                            }
                                        }
        );

        // manifest.xml 硬件加速 hardwareAccelerated = "true"

        //webview.setBackgroundColor(Color.parseColor("#00000000"));
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        return webview;
    }

    private void showProgressDialog() {
        if(webview.getVisibility() != View.INVISIBLE && webview.getVisibility() != View.GONE) {
            progressDialog = new ProgressDialog(this.context);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setMessage(context.getString(R.string.webcfg_dialog));
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }
    }
}
